package com.example.smartwaterapi.security;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.smartwaterapi.entity.User;
import com.example.smartwaterapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Spring Security用户服务
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;
    
    // 使用构造器注入
    @Autowired
    public UserDetailsServiceImpl(@Lazy UserService userService) { // 添加@Lazy注解
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = null;
        
        // 检查username是否为数字ID
        try {
            if (username.matches("^\\d+$")) {
                // 如果是数字，则按ID查询
                Long userId = Long.parseLong(username);
                log.debug("尝试通过ID查询用户: {}", userId);
                user = userService.getById(userId);
                
                if (user != null) {
                    log.debug("通过用户ID找到用户: {}", userId);
                    
                    // 确保用户ID正确设置
                    if (user.getId() == null) {
                        log.warn("用户ID为null，手动设置为: {}", userId);
                        user.setId(userId);
                    }
                    
                    return createSecurityUser(user);
                }
            }
        } catch (Exception e) {
            log.error("通过ID查询用户失败: {}", e.getMessage());
        }
        
        // 尝试通过手机号查询
        try {
            LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
            phoneWrapper.eq(User::getPhone, username);
            user = userService.getOne(phoneWrapper);
            
            if (user != null) {
                log.debug("通过手机号找到用户: {}", username);
                return createSecurityUser(user);
            }
        } catch (Exception e) {
            log.error("通过手机号查询用户失败: {}", e.getMessage());
        }
        
        // 尝试通过微信openid查询
        try {
            LambdaQueryWrapper<User> openidWrapper = new LambdaQueryWrapper<>();
            openidWrapper.eq(User::getOpenid, username);
            user = userService.getOne(openidWrapper);
            
            if (user != null) {
                log.debug("通过openid找到用户: {}", username);
                
                // 如果通过openid找到用户但ID为null，尝试通过openid直接查询ID
                if (user.getId() == null && user.getOpenid() != null) {
                    Long userId = userService.getUserIdByOpenid(user.getOpenid());
                    if (userId != null) {
                        log.info("通过openid直接查询到用户ID: {}", userId);
                        user.setId(userId);
                    }
                }
                
                return createSecurityUser(user);
            }
        } catch (Exception e) {
            log.error("通过openid查询用户失败: {}", e.getMessage());
        }
        
        log.error("找不到用户: {}", username);
        throw new UsernameNotFoundException("找不到用户: " + username);
    }
    
    /**
     * 创建SecurityUser对象，并确保用户ID有效
     */
    private SecurityUser createSecurityUser(User user) {
        if (user == null) {
            throw new UsernameNotFoundException("用户对象为null");
        }
        
        if (user.getId() == null) {
            log.error("创建SecurityUser失败: 用户ID为null, openid={}, nickname={}", 
                    user.getOpenid(), user.getNickname());
            
            // 尝试修复
            if (user.getOpenid() != null) {
                Long userId = userService.getUserIdByOpenid(user.getOpenid());
                if (userId != null) {
                    log.info("修复用户ID成功: {}", userId);
                    user.setId(userId);
                } else {
                    log.error("无法修复用户ID, openid={}", user.getOpenid());
                    throw new UsernameNotFoundException("用户ID无效");
                }
            } else {
                throw new UsernameNotFoundException("用户ID为null且无法通过openid修复");
            }
        }
        
        return new SecurityUser(user);
    }
} 